<template>
  <div class="app-container">
    <div class="action-container">
      <el-button type="primary" @click="handleCreateSubscribeEvent">增加<i class="el-icon--right"></i></el-button>
    </div>
    <div class="filter-container">
      <el-select @change='handleFilter' style="width: 120px" class="filter-item" v-model="listQuery.f_eq_orgId" placeholder="机关/科室">
        <el-option label="全部科室" value=""></el-option>
        <el-option v-for="item in orgList" :key="item.id" :label="item.name" :value="item.id">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" type="success" icon="el-icon-search" @click="resetFiler">重置</el-button>
    </div>

    <el-table :data="list" v-loading.body="listLoading" element-loading-text="数据正在加载中，请稍后..." border fit highlight-current-row>
      <el-table-column label="序号" width="80" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.id}}</span>
        </template>
      </el-table-column>
      <el-table-column label="机关/科室" width="200">
        <template slot-scope="scope">
          {{(scope.row.organization || {}).name || '-'}}
        </template>
      </el-table-column>
      <el-table-column label='用户' width="200">
        <template slot-scope="scope">
          {{(scope.row.user || {}).name || '-'}}
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button type="" size="small" @click="handleUpdateSubscribeEvent(scope.row)">修改<i class="el-icon--right"></i></el-button>
          <el-button type="warning" size="small" @click="handleDeleteSubscribeEvent(scope.row.id)">删除<i class="el-icon--right"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <div v-show="!listLoading" class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page.sync="listQuery.page"
                     :page-sizes="[10,20,30,50]" :page-size="listQuery.size" layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="subscribe" label-position="left" label-width="120px" style='width: 400px; margin-left:50px;'>
        <el-form-item label="ID" prop="type">
          <span>{{subscribe.id}}</span>
        </el-form-item>
        <el-form-item label="机关/科室" prop="orgId">
          <el-select v-model="subscribe.orgId">
            <el-option v-for="item in orgList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="userId">
          <el-select v-model="subscribe.userId" >
            <el-option v-for="item in userList" :key="item.id" :label="item.name" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <!--
                <el-form-item label="地址" prop="title">
                  <el-input v-model="device.address"></el-input>
                </el-form-item>
        -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="tryCreateSubscribe">确定</el-button>
        <el-button v-else type="primary" @click="tryUpdateSubscribe">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { MessageBox } from 'element-ui'
import { getSubscribeList, createSubscribe, updateSubscribe, deleteSubscribe } from '@/api/alert'
import { getOrgList, getUserListOfOrg } from '@/api/org'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      total: null,
      listQuery: {
        page: 1,
        size: 20,
        f_eq_orgId: ''
      },
      subscribe: {
        id: undefined,
        orgId: 1,
        userId: ''
      },
      orgList: [],
      userList: [],
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        create: '增加',
        update: '修改'
      },
      rules: {
        orgId: [{ required: true, message: '科室机关不能为空。', trigger: 'change' }],
        userId: [{ required: true, message: '用户不能为空。', trigger: 'change' }]
      }
    }
  },
  filters: {
  },
  created() {
    this.fetchOrgList()
    this.fetchData()
  },
  methods: {
    fetchOrgList() {
      getOrgList().then(response => {
        this.orgList = response.data
      })
    },
    fetchUserList(corpId) {
      getUserListOfOrg(corpId).then(response => {
        this.userList = response.data
      }).catch(() => {
        this.userList = []
      })
    },
    fetchData() {
      this.listLoading = true
      getSubscribeList(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.total
        this.listLoading = false
      }).catch(() => {
        this.listLoading = false
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.fetchData()
    },
    resetFiler() {
      if (!this.$route.query.corpId) {
        this.listQuery.f_eq_corpId = ''
      }
      this.listQuery.page = 1
      this.listQuery.size = 20
      this.fetchData()
    },
    handleSizeChange(val) {
      this.listQuery.size = val
      this.fetchData()
    },
    handleCurrentChange(val) {
      this.listQuery.page = val
      this.fetchData()
    },
    handleCreateSubscribeEvent() {
      //更新区域和用户列表
      this.fetchOrgList()
      this.fetchUserList()

      this.subscribe.id = undefined

      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryCreateSubscribe() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          createSubscribe(this.subscribe).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '创建成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleUpdateSubscribeEvent(row) {
      const t = Object.assign({}, row) // copy obj

      //更新区域和用户列表
      this.fetchOrgList(t.corpId)
      this.fetchUserList(t.corpId)

      this.subscribe.id = t.id
      this.subscribe.orgId = t.orgId
      this.subscribe.userId = t.userId

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    tryUpdateSubscribe() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const sub = Object.assign({}, this.subscribe)
          updateSubscribe(sub).then(() => {
            this.dialogFormVisible = false
            this.$notify({ title: '成功', message: '更新成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }
      })
    },
    handleDeleteSubscribeEvent(id) {
      MessageBox.confirm('请确认是否要删除该记录？', '操作确认', { confirmButtonText: '是', cancelButtonText: '否', type: 'warning' })
        .then(() => {
          deleteSubscribe(id).then(() => {
            this.$notify({ title: '成功', message: '删除成功', type: 'success', duration: 2000 })
            this.fetchData()
          })
        }, () => {})
    }
  }
}
</script>
